// pages/ucenter/person/publish/publish.js
const util = require('../../../../../utils/util.js');
const api = require('../../../../../config/api.js');
var getOrderByOrderNumInterval = null;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    descDialog: { "show": false, "type": "" },
    photoDialogShow: false,// 授权弹窗
    centerid: '',
    shimichecked: false,// 是否隐私
    title: '',// 副标题
    subheading: '',// 副标题
    latitude: '',//当前位置x轴
    longitude: '',//当前位置y轴
    openStoreDialogShow: false,// 未开通店铺的弹窗
    preferentialOpenStoreDialogShow: false,// 免费开通店铺的弹窗
    selectAllLable: [],// 选中的类目标签
    selectLableTextArray: [],// 选中的类目标签文字版
    storeDialogShowIndex: "",// 点击分销的index
    openStoreInfo: {},// 开通店铺的信息
    joinCommissionShow: false,// 加入店铺弹窗
    shareInfo: { "shareImageDialogShow": false, "shareImage": "" , "circleid": ""},// 分享的图片信息
    //shareInfo: { "shareImageDialogShow": true, "shareImage": "https://image.xingqubaike.com:8443/minicard/canvas/2019/07/23/ac5c134a-db23-4380-8433-6ead3554b357.png", "circleid": 774 },// 分享的图片信息

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    _this.getweizhi();
  },

  /**
   * 获取用户位置信息
   */
  getweizhi: function () {
    var _this = this;
    wx.getLocation({
      type: "wgs84",
      success: function (res) {
        _this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        _this.selectByCreateInterestQuery(res.latitude, res.longitude);
      },
      fail: function () {
        // 拒绝授权
        _this.selectByCreateInterestQuery();
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 跳转项目标签
   */
  doitemlabel: function (event) {
    var _this = this;
    wx.navigateTo({
      url: 'itemlabel/itemlabel?selectAllLable=' + JSON.stringify(_this.data.selectAllLable),
    })
  },
  /**
   * 下一步
   */
  savenext: function () {
    var _this = this;
    var title = _this.data.title;
    var shimichecked = _this.data.shimichecked;
    var subheading = _this.data.subheading;
    var selectAllLable = _this.data.selectAllLable;
    let param = {};
    var latitude = _this.data.latitude;
    var longitude = _this.data.longitude;
    if (selectAllLable.length <= 0) {
      wx.showToast({
        title: '请选择圈子的类目标签',
        icon: 'none',
        duration: 2000
      })
    } else if (title == '') {
      wx.showToast({
        title: '请输入您要创建的圈子主标题',
        icon: 'none',
        duration: 2000
      })
    } else {
      var openid = app.globalData.logininfo.openid;
      if (openid != null && openid != "") {
        wx.showLoading({
          title: '提交中',
        })
        // 已登录
        util.post(api.fetchToken()).then(function (res) {
          if (res.access_token != '') {
            return Promise.resolve({
              access_token: res.access_token
            });
          }
        }).then(function (res) {
          param.access_token = res.access_token;
          param.title = title;
          param.myprivate = shimichecked ? 1 : 0;
          param.subheading = subheading;
          param.openid = openid;
          param.itemlabelData = JSON.stringify(selectAllLable);
          param.latitude = String(latitude);
          param.longitude = String(longitude);
          util.post(api.Interest_insertInterest, param).then(function (res2) {
            if (res2.code == 200) {
              var json = res2.result.json;
              var circleid = json.id;
              var energyInfoResults = json.energyInfoResults;
              wx.redirectTo({
                url: '../editdetails/editdetails?circleid=' + circleid + "&energyInfoResults=" + energyInfoResults
              })
            } else {
              wx.showToast({
                title: '数据异常',
                icon: 'none',
                duration: 2000
              })
            }
            wx.hideLoading();
          })
        });
      }
    }
  },
  onPrivateChange({ detail }) {
    // 需要手动对 checked 状态进行更新
    this.setData({ shimichecked: detail });
    wx.showToast({
      title: '设置成功',
      icon: '',     //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
      duration: 2000,      //停留时间
    })
  },
  getTitle: function (e) {
    var val = e.detail.value;
    this.setData({
      title: val
    });
  },
  getSubheading: function (e) {
    var val = e.detail.value;
    this.setData({
      subheading: val
    });
  },

  /**
   * 圈子分销
   */
  circleDistribution: function (e) {
    // 未开通店铺弹窗，进行弹窗
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var circleid = _this.data.commissionList[index].dataId;
    // 校验当前用户是否有开通店铺
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var param = {};
        param.access_token = res.access_token;
        param.openid = openid;
        param.circleid = circleid;
        util.post(api.My_checkUserOpenStoreApi, param).then(function (res2) {
          if (res2.code == 200) {
            var obj = res2.result.obj;
            if (!obj.isOpen) {
              // 未开通
              var openStorePrice = obj.openStorePrice;// 开通原价
              var storePreferentialPrice = obj.storePreferentialPrice;
              var preferentialPrice = storePreferentialPrice.preferentialPrice;// 开通优惠价格
              var openText = "";
              var openPrice = 0;
              var openType = 1;
              if (preferentialPrice > 0 && preferentialPrice < openStorePrice) {
                openText = "优惠";
                openType = 1;
                openPrice = openStorePrice - preferentialPrice;
              } else if (preferentialPrice > 0 && preferentialPrice == openStorePrice) {
                openText = "免费";
                openType = 2;
                openPrice = 0;
              } else {
                openText = "";
                openPrice = openStorePrice;
                openType = 3;
              }
              obj.openText = openText;
              obj.openPrice = openPrice;
              obj.openType = openType;
              _this.setData({
                openStoreInfo: obj
              })
              _this.openStoreDialogShow();
            } else {
              var distributionCount = obj.distributionCount;
              if (distributionCount <= 0) {
                _this.joinCommissionShow();
              } else {
                var distributionDetails = obj.distributionDetails;
                var shareImage = distributionDetails.shareImageIp + distributionDetails.shareImageUrl;
                _this.setData({
                  ["shareInfo.circleid"]: circleid,
                  ["shareInfo.shareImage"]: shareImage,
                  ["shareInfo.shareImageDialogShow"]: true
                })
              }
            }
            _this.setData({
              storeDialogShowIndex: index
            })
          }
        })
      });
    }
  },

  /**
   * 关闭分销的分享图片
   */
  shareImageDialogClose: function () {
    var _this = this;
    util.showToast("此分销项目已入驻你的店铺，请及时推广分享", "none");
    _this.setData({
      shareInfo: { "shareImageDialogShow": false, "shareImage": "", "circleid": "" }
    })
  },

  /**
   * 进入圈子详情页
   */
  navigateToCircledetails2: function (e) {
    var _this = this;
    var circleid = e.currentTarget.dataset.circleid;
    _this.navigateToCircledetails(circleid);
  },

  /*
    * 进入圈子详情页
     */
  navigateToCircledetails: function (circleid) {
    wx.navigateTo({
      url: '../../personcenter/editdetails/circledetails/circledetails?circleid=' + circleid + "&commissionJoinType=2",
    })
  },

  /**
   *  未开通店铺弹窗
   */
  openStoreDialogShow: function () {
    var _this = this;
    _this.setData({
      openStoreDialogShow: true
    })
  },

  /**
   *  未开通店铺弹窗关闭
   */
  openStoreDialogClose: function () {
    var _this = this;
    _this.setData({
      openStoreDialogShow: false,
      storeDialogShowIndex: "",
      openStoreInfo: {}
    })
  },

  /**
   *  开通店铺弹窗
   */
  preferentialOpenStoreDialogShow: function () {
    var _this = this;
    _this.setData({
      preferentialOpenStoreDialogShow: true,
      openStoreDialogShow: false
    })
  },

  /**
   *  开通店铺弹窗关闭
   */
  preferentialOpenStoreDialogClose: function () {
    var _this = this;
    _this.setData({
      preferentialOpenStoreDialogShow: false,
      storeDialogShowIndex: "",
      openStoreInfo: {}
    })
  },

  /**
   * 获取分销圈子请求
   */
  selectByCreateInterestQuery: function (latitude = null, longitude = null) {
    var _this = this;
    var param = {};
    param.latitude = latitude;
    param.longitude = longitude;
    util.post(api.Interest_selectByCreateInterest, param).then(function (res2) {
      if (res2.code == 200) {
        var list = res2.result.list;
        _this.setData({
          commissionList: list
        })
      }
    })
  },

  /**
   * 加入店铺弹窗
   */
  joinCommissionShow: function () {
    var _this = this;
    _this.setData({
      joinCommissionShow: true
    })
  },

  /**
   * 加入店铺弹窗关闭
   */
  joinCommissionClose: function () {
    var _this = this;
    _this.setData({
      joinCommissionShow: false,
      storeDialogShowIndex: ""
    })
  },

  /**
   * 开通店铺
   */
  preferentialOpenStoreDialogSuccess: function () {
    var _this = this;
    var openStoreInfo = _this.data.openStoreInfo;
    var openStorePrice = openStoreInfo.openStorePrice;// 开通原价
    var preferentialPrice = openStoreInfo.storePreferentialPrice.preferentialPrice;// 开通优惠价格
    var payStorePrice = openStorePrice - preferentialPrice;// 需要支付的金额
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      wx.showLoading({
        title: '开通店铺中',
      })
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var param = {};
        param.access_token = res.access_token;
        param.payStorePrice = payStorePrice;// 用于校验页面展示金额是否和实际支付金额一致
        param.openid = openid;
        util.post(api.My_openStoreApi, param).then(function (res2) {
          if (res2.code == 200) {
            var buyJoinState = res2.result.buyJoinState;
            var json = res2.result.obj;
            var orderNum = json.orderNum;
            var totalMoney = json.totalMoney;
            if (buyJoinState == 1) {
              // 不需要支付
              util.showToast("开通店铺成功~", "success");
              _this.preferentialOpenStoreDialogClose();
            } else {
              // 需要调用微信支付
              _this.wechatCallbackBusiness(orderNum, totalMoney);
            }
          } else {
            util.showToast(res2.message, "none");
          }
          wx.hideLoading();
        })
      });
    }
  },

  /**
   * 微信支付回调：这个应该是支付后自动触发，但是开发阶段，就代码触发
   */
  wechatCallbackBusiness: function (orderNum, totalMoney) {
    var _this = this;
    var param = {};
    param.orderNum = orderNum;
    param.actualPrice = totalMoney;
    param.outTradeNo = new Date().getTime();
    util.post(api.Interest_WechatCallback, param, "application/x-www-form-urlencoded;charset=UTF-8").then(function (res) {
      wx.showLoading({
        title: '支付中',
      })
      getOrderByOrderNumInterval = setInterval(function () {
        _this.getOrderByOrderNum(orderNum);
      }, 1000);
    })
  },

  /**
   * 通过订单号获取订单信息
   */
  getOrderByOrderNum: function (orderNum) {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    util.post(api.fetchToken()).then(function (res1) {
      if (res1.access_token != '') {
        return Promise.resolve({
          access_token: res1.access_token
        });
      }
    }).then(function (res2) {
      var param = {};
      param.openid = openid;
      param.orderNum = orderNum;
      param.access_token = res2.access_token;
      util.post(api.Interest_GetOrderByOrderNum, param).then(function (res) {
        if (res.code == 200) {
          var order = res.result.obj;
          if (order.orderStatus == 100) {
            // 支付成功
            util.showToast("开通店铺成功~", "success");
            _this.preferentialOpenStoreDialogClose();
            clearInterval(getOrderByOrderNumInterval);
          }
        }
        wx.hideLoading();
      })
    })
  },

  /**
   * 确定分销
   */
  joinCommissionSuccess: function () {
    var _this = this;
    var storeDialogShowIndex = _this.data.storeDialogShowIndex;
    var circleid = _this.data.commissionList[storeDialogShowIndex].dataId;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      wx.showLoading({
        title: '提交中',
      })
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var param = {};
        param.openid = openid;
        param.circleid = circleid;
        param.access_token = res.access_token;
        param.commissionJoinType = 1;
        util.post(api.Interest_joinCommissionInterest, param).then(function (res2) {
          wx.hideLoading();
          if (res2.code == 200) {
            var obj = res2.result.obj;
            _this.setData({
              ["shareInfo.circleid"]: circleid,
              ["shareInfo.shareImage"]: obj,
              ["shareInfo.shareImageDialogShow"]: true
            })
            _this.joinCommissionClose();
          } else {
            util.showToast(res2.message, "none");
          }
        })
      });
    }
  },

  /**
   * 分享
   */
  onShareAppMessage: function (e) {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var nickName = app.globalData.logininfo.userInfo.nickName;
    if (e.from == "button") {
      var shareImage = _this.data.shareInfo.shareImage;
      var circleid = e.target.dataset.circleid;
      return {
        title: nickName + "邀请您加入一个很棒的圈子",
        path: 'pages/home/shareJump/shareJump?id=' + circleid + "&type=" + util.getShareType("commissionCircle") + "&shareOpenid=" + openid + "&isCheckLogin=1&circleid=" + circleid,
        imageUrl: shareImage
      }
    }
  },

/**
 * 保存图片到相册
 */
  onSavePicClick: function (e) {
    var _this = this;
    var downloadUrl = e.target.dataset.path;
    // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.writePhotosAlbum" 这个 scope  
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.writePhotosAlbum'] == false) {
          // 没有授权《保存图片》权限
          _this.setData({
            photoDialogShow: true
          })
        } else {
          //已经授权《保存图片》权限
          util.downloadImage(downloadUrl);
        }
      },
      fail(res) {
      }
    })
  },

  /**
   * 关闭没有授权《保存图片》弹窗
   */
  photoDialogClose: function(){
    var _this = this;
    _this.setData({
      photoDialogShow: false
    })
  },

  /**
   * 《保存图片》未授权的弹窗确认动作
   */
  photoDialogSuccess: function(e) {
    var _this = this;
    var downloadUrl = e.target.dataset.path;
    wx.openSetting({
      success: function (data) {
        if (data.authSetting["scope.writePhotosAlbum"] == true) {
          // 授权成功
          _this.photoDialogClose();
          util.downloadImage(downloadUrl)
        } else {
          // 授权失败
          _this.photoDialogClose();
        }
      }
    })
  },

  /**
   * 打开弹窗
   */
  openDialog: function(e){
    var _this = this;
    var type = e.target.dataset.type;
    _this.setData({
      ["descDialog.show"]: true,
      ["descDialog.type"]: type
    })
  },
  /**
   * 关闭弹窗
   */
  closeDialog: function (e) {
    var _this = this;
    _this.setData({
      ["descDialog.show"]: false,
      ["descDialog.type"]: ""
    })
  },

  switchInterest: function () {
    app.globalData.distribution = true;
    wx.switchTab({
      url: '/pages/interest/interest'
    })
  }
})

